package com.carter.springframework.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import com.carter.springframework.beans.factory.DisposableBean;
import com.carter.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Method;

/**
 * bean销毁方法的适配器
 */
public class DisposableBeanAdapter implements DisposableBean {
    private final Object bean;
    private final String beanName;
    private final BeanDefinition beanDefinition;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.beanDefinition = beanDefinition;
    }

    @Override
    public void destroy() throws Exception {
        //实现了DisposableBean接口
        if (bean instanceof DisposableBean){
            ((DisposableBean) bean).destroy();
        }
        //配置了销毁方法
        if (StrUtil.isNotBlank(beanDefinition.getDestroyMethodName()) && !(bean instanceof DisposableBean && "destroy".equals(beanDefinition.getDestroyMethodName()))) {
            Method destroyMethod = beanDefinition.getBeanClass().getMethod(beanDefinition.getDestroyMethodName());
            destroyMethod.invoke(bean);
        }

    }
}
